package Model.InboxMessages;

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * Servlet implementation class MessageServerlet
 */
@WebServlet("/inbox")
public class InboxServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public InboxServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		int userid = Integer.parseInt(request.getParameter("userid"));
		int start = Integer.parseInt(request.getParameter("start"));
		request.setAttribute("tryingAgain", false);
		RequestDispatcher dispatcher;
		ArrayList<SimpleMessage> msgs = Inbox.getMessages(userid,start);
		if(msgs.size() > 0)
		{
			JSONObject result = new JSONObject();

			JSONArray myJson = new JSONArray(msgs);
			System.out.print(myJson);
			try {
				result.put("messages",myJson);
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			response.getWriter().print(result.toString());
			
		} else {
			//response.getWriter().print('{"time":"2011-11-14","msgNum":1,"from":"nameof","msg":"test3"}');
		}
	}
}
